import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/style/app_style.dart';
import '../../../common/style/extension_util.dart';

enum TextFormFieldWidgetType {
  edit,
  choose,
}
enum TextFormFiledInputBorder{
  underline,
  roundRect,
  stadium,
  none
}
enum TextFormFiledValidatorType{
  phone,
  number,
  email,
  numberPoint,
  text
}

class XCColors{
  static Color gray2 = const Color(0xFF999999);
  static Color gray1 = const Color(0xFF212121);
}

class TextFormFieldWidget extends StatefulWidget {
  TextFormFieldWidget({
    super.key,
    this.title,
    this.titleStyle,
    this.fontSize = 14,
    this.subTitle,
    this.subTitleStyle,
    this.hintText,
    this.hintTextStyle,
    this.controller,
    this.spacing,
    this.titleWidth,
    this.subTitleWidth,
    this.showStar = false,
    this.maxLines = 1,
    this.subTitleMaxLines = 1,
    this.minLines = 1,
    this.subTitleMaxLength,
    this.enabled = true,
    this.prefixWidget,
    this.suffixWidget,
    this.onChanged,
    this.onTap,
    this.onEditingComplete,
    this.focusNode,
    this.onSaved,
    this.onFieldSubmitted,
    this.onTapTips,
    this.keyboardType,
    this.showCleanButton = false,
    this.inputFormatters,
    this.subTitleTextAlign = TextAlign.right,
    this.type = TextFormFieldWidgetType.edit,
    this.direction = Axis.horizontal,
    this.chooseModeIcon,
    this.padding,
    this.textInputAction,
    this.autofocus,
    this.customFiled,
    this.showArrowIcon = true,
    this.inputBorder = TextFormFiledInputBorder.underline,
    this.contentPadding,
    this.validator,
    this.validatorType = TextFormFiledValidatorType.text
  });

  final EdgeInsetsGeometry? padding;
  final EdgeInsetsGeometry? contentPadding;

  final TextEditingController? controller;

  /// 标题文字，左或上
  final String? title;
  final TextStyle? titleStyle;

  ///
  final double fontSize;

  /// 子标题文字（内容），右或下
  String? subTitle;
  final TextStyle? subTitleStyle;

  ///提示文字
  final String? hintText;
  final TextStyle? hintTextStyle;

  /// 显示星号
  final bool showStar;

  /// title和subTitle间距，默认水平24，垂直4
  final double? spacing;

  /// title宽度，默认titleWidth==subTitleWidth
  final double? titleWidth;

  /// subTitle宽度，默认titleWidth==subTitleWidth
  final double? subTitleWidth;

  /// 输入框类型
  final TextFormFieldWidgetType type;
  final int? maxLines;
  final int? subTitleMaxLines;
  ///设置最小高度可以增大输入框显示
  final int? minLines;
  final int? subTitleMaxLength;
  final FocusNode? focusNode;

  /// type == XCTextFormFieldType.choose，输入框始终不能输入，enabled无效
  final bool? enabled;
  final bool showCleanButton;
  final Axis direction;
  final TextAlign subTitleTextAlign;
  final TextInputType? keyboardType;
  final List<TextInputFormatter>? inputFormatters;
  final Widget? prefixWidget;
  final Widget? suffixWidget;

  /// onTapTips != null，显示tips图标
  final GestureTapCallback? onTapTips;
  final ValueChanged<String>? onChanged;
  final GestureTapCallback? onTap;
  final VoidCallback? onEditingComplete;
  final ValueChanged<String>? onFieldSubmitted;
  final FormFieldSetter<String>? onSaved;

  final Widget? chooseModeIcon;
  final TextInputAction? textInputAction;
  final bool? autofocus;
  final Widget? customFiled;
  final bool showArrowIcon;

  final FormFieldValidator<dynamic>? validator;
  final TextFormFiledValidatorType validatorType;
  ///边框类型
  final TextFormFiledInputBorder? inputBorder;
  @override
  State<TextFormFieldWidget> createState() => _XCTextFormFieldState();
}

class _XCTextFormFieldState extends State<TextFormFieldWidget> {
  bool _showCleanButton = false;
  final FocusNode _focusNode = FocusNode();
  final ScrollController _scrollController = ScrollController();
  late final TextEditingController _controller = TextEditingController();

  TextEditingController get _getController => widget.controller ?? _controller;
  FocusNode get _getFocusNode => widget.focusNode ?? _focusNode;

  @override
  void initState() {
    super.initState();
    if(widget.subTitle != null && widget.controller == null){
      _getController.text = widget.subTitle!;
    }
    _getFocusNode.addListener(() {
      if (_getFocusNode.hasFocus == false) {
        _scrollController.jumpTo(0);
        if (widget.onEditingComplete != null) {
          widget.onEditingComplete!();
        }
      }
    });
    _getController.addListener(
          () {
        String newValue = _getController.text;
        if (newValue.isNotEmpty && _showCleanButton == false) {
          setState(() {
            _showCleanButton = true;
          });
        } else if (newValue.isEmpty && _showCleanButton == true) {
          setState(() {
            _showCleanButton = false;
          });
        }
        widget.subTitle = newValue;
        if (widget.onChanged != null) {
          widget.onChanged!(newValue);
        }
      },
    );
  }

  @override
  void dispose() {
    _getController.dispose();
    _scrollController.dispose();
    _focusNode.dispose();

    super.dispose();
  }

  double _spacing() => widget.spacing ?? (widget.direction == Axis.horizontal ? 12 : 4);

  double get _fontSize => widget.fontSize;
  final double _cleanButtonSize = 16;
  final double _cleanButtonSpacing = 5;

  bool _isEditingAndHasValue() {
    return  _getController.text.isNotEmpty;
    return _getFocusNode.hasFocus || _getController.text.isNotEmpty;
  }
  InputBorder? _getBorder() {
    bool active = _isEditingAndHasValue();
    switch(widget.inputBorder){
      case TextFormFiledInputBorder.underline:
        return UnderlineInputBorder(borderSide: BorderSide(color: active == true ? AppColor.primaryColor : AppColor.textColor1));
      case TextFormFiledInputBorder.roundRect:
        return OutlineInputBorder(borderSide: BorderSide(color: active == true ? AppColor.primaryColor : AppColor.textColor1),borderRadius: BorderRadius.circular(0));
      default:
        return const OutlineInputBorder(borderSide: BorderSide(width: 0, style: BorderStyle.none));
        break;
    }
    return UnderlineInputBorder(borderSide: BorderSide(color: active == true ? AppColor.primaryColor : AppColor.textColor1));
  }


  Widget _getTextFormField() {
    bool enabled = widget.enabled == true && widget.type == TextFormFieldWidgetType.edit;
    _showCleanButton = _getController.text.isNotEmpty && enabled == true;

    return TextFormField(
      autofocus: widget.autofocus ?? false,
      controller: _getController,
      scrollController: _scrollController,
      cursorColor: const Color(0xFF999999),
      maxLines: widget.subTitleMaxLines,
      minLines: widget.minLines ?? 1,
      maxLength: widget.subTitleMaxLength,
      enabled: enabled,
      focusNode: _getFocusNode,
      textAlign: widget.subTitleTextAlign,
      keyboardType: widget.keyboardType,
      inputFormatters: widget.inputFormatters,
      style: _getSubTitleTextStyle(),
      scrollPadding: EdgeInsets.zero,
      textInputAction: widget.textInputAction,
      textAlignVertical: TextAlignVertical.bottom,
      decoration: InputDecoration(

        isCollapsed: true,
        hintText: widget.hintText,
        border: _getBorder(),
        focusedBorder: _getBorder(),
        enabledBorder: _getBorder(),
        disabledBorder: _getBorder(),
        counterText: "",
        hintStyle: _getHintTextStyle(),
        // contentPadding: EdgeInsets.symmetric(horizontal: 12),
        //   contentPadding:EdgeInsets.zero,
        contentPadding: widget.contentPadding ?? EdgeInsets.symmetric(vertical: 8.h,horizontal: 0),
        suffixIconConstraints:
        BoxConstraints(maxWidth: _cleanButtonSize + _cleanButtonSpacing * 2, maxHeight: _cleanButtonSize),
        suffixIcon: _showCleanButton & widget.showCleanButton == false
            ? null
            : IconButton(
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
          padding: EdgeInsets.zero,
          onPressed: () {
            setState(() {
              _getController.clear();
              _showCleanButton = false;
            });
          },
          icon: const Icon(Icons.cancel, color: Color(0xFFB5B5B5)),
          iconSize: _cleanButtonSize,
        ),
      ),
      onSaved: widget.onSaved,
      onEditingComplete: widget.onEditingComplete,
      onFieldSubmitted: widget.onFieldSubmitted,
        // validator: (value) {
        //   if(widget.validator != null) {
        //     return widget.validator!.call(value);
        //   }
        //   if(value == null){
        //     return "请输入";
        //   }
        //   switch(widget.validatorType){
        //     case TextFormFiledValidatorType.phone:
        //       if(!GetUtils.isPhoneNumber(value)){
        //         SmartDialog.showToast("msg");
        //       }
        //        // GetUtils.isPhoneNumber(value) ? value : null;
        //     case TextFormFiledValidatorType.number:
        //       GetUtils.isNum(value) ? value : null;
        //     case TextFormFiledValidatorType.email:
        //        GetUtils.isEmail(value) ? value : null;
        //     case TextFormFiledValidatorType.numberPoint:
        //        GetUtils.isNum(value) ? value : null;
        //     case TextFormFiledValidatorType.text:
        //        return value.isEmpty ? widget.hintText: null;
        //
        //   }
        //
        //  return null;
        // }
    );
  }

  Widget _getTitleWidget() {
    return SizedBox(
      width: widget.titleWidth,
      child: Align(
        widthFactor: 1.0,
        heightFactor: 1.0,
        alignment: Alignment.centerLeft,
        child: RichText(
          text: TextSpan(
            style: _getTitleTextStyle(),
            children: [
              TextSpan(
                text: widget.showStar ? '* ' : "",
                style: TextStyle(fontSize: _fontSize, color: AppColor.primaryColor),
                children: [
                  widget.onTapTips == null
                      ? const TextSpan()
                      : WidgetSpan(
                    alignment: PlaceholderAlignment.middle,
                    child: SizedBox(
                      width: _fontSize + _cleanButtonSpacing * 2,
                      child: Container(
                        color: Colors.transparent,
                        child: onClick(
                          onTap: widget.onTapTips,
                          child: Image.asset("name"),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
          TextSpan(
            text: widget.title,
            style: _getTitleTextStyle())

            ],
          ),
          overflow: TextOverflow.ellipsis,
          maxLines: widget.maxLines,
        ),
      ),
    );
  }

  static Widget onClick({VoidCallback? onTap, Widget? child}) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: child,
    );
  }

  Widget _getSubTitleWidget() {

    return widget.type == TextFormFieldWidgetType.choose
        ? Text(
      (widget.subTitle ?? widget.hintText) ?? "",
      overflow: TextOverflow.ellipsis,
      maxLines: widget.subTitleMaxLines,
      textAlign: widget.subTitleTextAlign,
      style: widget.subTitle != null ? _getSubTitleTextStyle() : _getHintTextStyle(),
    ).addPadding(widget.contentPadding ?? EdgeInsets.symmetric(vertical: 12))
        : widget.customFiled ?? _getTextFormField();

    return SizedBox(
      width: widget.subTitleWidth,
      child: widget.type == TextFormFieldWidgetType.choose
          ? Text(
        (widget.subTitle ?? widget.hintText) ?? "",
        overflow: TextOverflow.ellipsis,
        maxLines: widget.subTitleMaxLines,
        textAlign: widget.subTitleTextAlign,
        style: widget.subTitle != null ? _getSubTitleTextStyle() : _getHintTextStyle(),
      )
          : widget.customFiled ?? _getTextFormField(),
    );
  }

  _getTitleTextStyle() {
    return widget.titleStyle ?? TextStyle(fontSize: _fontSize, color: XCColors.gray2);
  }

  _getSubTitleTextStyle() {
    return widget.subTitleStyle ??
        TextStyle(
          fontSize: _fontSize,
          color: widget.type == TextFormFieldWidgetType.choose
              ? XCColors.gray1
              : (widget.enabled == true ? XCColors.gray1 : XCColors.gray2),
        );
  }

  _getHintTextStyle() {
    return widget.hintTextStyle ??
        TextStyle(
          fontSize: _fontSize,
          color: XCColors.gray2,
          textBaseline: TextBaseline.alphabetic,
          overflow: TextOverflow.ellipsis,
        );
  }

  Widget _getSelectArrow() {
    if (widget.type == TextFormFieldWidgetType.choose && widget.showArrowIcon) {
      return widget.chooseModeIcon ??
          Container(
            margin: EdgeInsets.only(
              left: _cleanButtonSpacing,
            ),
            child: const Icon(Icons.arrow_forward_ios_rounded,size: 10,)
          );
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    return onClick(
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus();
        if (widget.type == TextFormFieldWidgetType.choose && widget.onTap != null) {
          widget.onTap!();
        }
      },
      child: widget.direction == Axis.horizontal
          ? Row(
        // crossAxisAlignment: CrossAxisAlignment.start,
        // mainAxisAlignment: MainAxisAlignment.spaceBetween,

        children: [
          widget.prefixWidget ?? Container(),
          // Expanded(
          //   flex: widget.titleWidth == null ? 1 : 0,
          //   child: _getTitleWidget(),
          // ),
          _getTitleWidget(),
          SizedBox(
            width: _spacing(),
          ),
          Expanded(
            // flex: widget.subTitleWidth == null ? 1 : 0,
            child: _getSubTitleWidget()
                // .addContainer(color: Colors.green),
          ),
          widget.suffixWidget ?? Container(),
          _getSelectArrow(),
        ],
      )
          : Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          widget.prefixWidget ?? Container(),
          Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _getTitleWidget(),
                SizedBox(
                  height: _spacing(),
                ),
                _getSubTitleWidget(),
              ],
            ),
          ),
          widget.suffixWidget ?? Container(),
          _getSelectArrow(),
        ],
      ),
    );
  }
}
